﻿using MyIServices;
using MyIServices.BASE;
using MyModels.Models;
using MyRepository.BASE;
using MyServices.BASE;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyServices
{
    public class SysUserInfoServices : BaseService<SysUserInfo>, ISysUserInfoServices
    {
        private readonly IBaseRepository<SysUserInfo> _dal;
        private readonly IBaseRepository<UserRole> _userRoleRepository;
        private readonly IBaseRepository<Role> _roleRepository;

        public SysUserInfoServices(IBaseRepository<SysUserInfo> dal,IBaseRepository<UserRole> userRoleRepository,IBaseRepository<Role> roleRepository)
        {
            _dal = dal;
            _userRoleRepository = userRoleRepository;
            _roleRepository = roleRepository;
            BaseDal = _dal;
        }
        public async Task<string> GetUserRoleNameStr(string loginName, string password)
        {
            string roleName = "";
            var user = (await Query(a=>a.LoginName==loginName&& a.LoginPwd==password)).FirstOrDefault();
            var roleList = await _roleRepository.Query(a=>a.IsDeleted==false);
            if (user != null) { 
                var userRole = await _userRoleRepository.Query(ur=>ur.UserId==user.Id);
                if (userRole.Count() > 0) {
                    var roleIds = userRole.Select(ur => ur.RoleId.ToString()).ToList();
                    var roles = roleList.Where(d => roleIds.Contains(d.Id.ToString()));

                    roleName = string.Join(",", roles.Select(r=>r.Name).ToArray());
                }
            }
            return roleName;
        }

        public async Task<SysUserInfo> SaveUserInfo(string loginName, string password)
        {
            var userInfo = new SysUserInfo(loginName,password);
            var model = new SysUserInfo();
            var userList = await Query(i => i.LoginName == loginName && i.LoginPwd == password);
            if (userList.Count > 0)
            {
                model = userList.FirstOrDefault();
            }
            else { 
                var id = await Add(userInfo);
                model = await QueryById(id);
            }

            return model!;
        }
    }
}
